<script setup>
import {
  onMounted,
  nextTick,
  ref,
  reactive,
  watch,
  computed,
  watchEffect,
  toRefs,
} from "vue";
import iconClose from "../../assets/img/关闭.png";
import { seriesQueriesNew } from "../../network/net.js";
import {
  formatTime,
  addHours,
  formatTimeStr,
  diffHours,
} from "../../utils/cTime.js";
import iconArrow from "../../assets/img/向上灰.png";
import Config from "../module/Class_Map.js";
import { chartInfo, smInfo } from "../../stores/chun.js";
import { bm, waveValue, bmName, smPngInfo, smRange } from "../../stores/chun.js";
import * as echarts from 'echarts';
const token = sessionStorage.getItem("token");

onMounted(() => { });

const rows = ref([
  {
    title: "小时",
    dw: "",
    data: [
      "08",
      "09",
      "10",
      "11",
      "12",
      "13",
      "14",
      "15",
      "16",
      "17",
      "18",
      "19",
      "20",
      "21",
      "22",
      "23",
      "00",
      "01",
      "02",
      "03",
      "04",
      "05",
      "06",
      "07",
      "08",
      "09",
      "10",
      "11",
      "12",
      "13",
      "14",
      "15",
      "16",
      "17",
      "18",
      "19",
      "20",
      "21",
      "22",
      "23",
      "00",
      "01",
      "02",
      "03",
      "04",
      "05",
      "06",
      "07",
      "08",
      "09",
      "10",
      "11",
      "12",
      "13",
      "14",
      "15",
      "16",
      "17",
      "18",
      "19",
      "20",
      "21",
      "22",
      "23",
      "00",
      "01",
      "02",
      "03",
      "04",
      "05",
      "06",
      "07",
    ],
    isShow: true,
  },
  {
    title: "海风",
    dw: "m/s",
    data: [],
    background: [],
    isShow: true,
  },
  {
    title: "风向",
    dw: "°",
    data: [],
    isShow: true,
  },
  {
    title: "海浪",
    dw: "m",
    data: [],
    background: [],
    isShow: true,
  },
  {
    title: "浪向",
    dw: "°",
    data: [],
    isShow: true,
  },
  {
    title: "海流",
    dw: "m/s",
    data: [],
    background: [],
    isShow: true,
  },
  {
    title: "流向",
    dw: "°",
    data: [],
    isShow: true,
  },
]);

const titles = ref([
  {
    title: "x",
    dw: "",
    isShow: true,
  },
  {
    title: "小时",
    dw: "",
    isShow: true,
  },
  {
    title: "海风",
    dw: "(m/s)",
    isShow: true,
  },
  {
    title: "风向",
    dw: "",
    isShow: true,
  },
  {
    title: "海浪",
    dw: "(m)",
    isShow: true,
  },
  {
    title: "浪向",
    dw: "",
    isShow: true,
  },
  {
    title: "海流",
    dw: "(m/s)",
    isShow: true,
  },
  {
    title: "流向",
    dw: "",
    isShow: true,
  },
]);

const date = ref(formatTime(new Date(), "yyyy-MM-dd"));

const day3 = ref([]);

const getWaveColor = (value) => {
  // 超过warnValue 红色
  if (value > waveValue.value) {
    return "#D0021B";
  } else {
    return "";
  }
}

for (let i = 0; i < 4; i++) {
  let width = 0;
  if (i === 0) {
    width = 16 / 72;
  } else if (i === 1) {
    width = 24 / 72;
  } else if (i === 2) {
    width = 24 / 72;
  } else {
    width = 8 / 72;
  }
  day3.value.push({
    date: formatTime(
      addHours(date.value.split(" ")[0] + " 00:00", i * 24)
    ).split(" ")[0],
    width,
  });
}

const getLinearGradient = (data) => {
  let str = "linear-gradient(to right,";
  data.forEach((item, idx) => {
    str += item + " ";
    if (idx != data.length - 1) {
      str += ",";
    }
  });
  str += ")";
  return str;
};

let num = ref(3);
let diff = ref(0);

const activeHeight = ref(0);
watch(
  [chartInfo, num],
  () => {


    if (chartInfo.isChart) {
      let smDate = formatTimeStr(smInfo.dateShumo);

      diff.value =
        diffHours(formatTime(new Date()).split(" ")[0] + " 08:00", smDate) + 8;

      activeHeight.value = 35 + num.value * 60 + 30;
      let typeArr = ["wave", "wind", "current"];
      // 获取当前时间和72小时后的时间
      let now = new Date();
      let end = addHours(now, 72);
      let nowStr = formatTime(
        addHours(formatTime(now).split(" ")[0] + " 08:00", -8)
      );
      let endStr = formatTime(
        addHours(formatTime(end).split(" ")[0] + " 08:00", -8)
      );

      let allP = [];
      typeArr.forEach((sType) => {
        allP.push(
          // seriesQueriesNew(
          //   token,
          //   sType, 
          //   nowStr,
          //   endStr,
          //   chartInfo.lat,
          //   chartInfo.lng,
          //   bmName.value
          // )
          seriesQueriesNew(
            token,
            {
              ...smRange[sType],
              startDateTime: nowStr,
              endDateTime: endStr,
              featureType: sType,
              latitude: chartInfo.lat,
              longitude: chartInfo.lng,
            }
          )
        );
      });
      const { wave, current_speed, wind_speed } = Config.scalarColor;

      Promise.all(allP).then((res) => {
        if (res[0].data.code == 200) {

          let waveData = res[0].data.data.waveDatas;
          rows.value[3].data = waveData.map((item) => {
            // item[0]
            if (item) {
              return item[0];
            } else {
              return 0;
            }
          });
          rows.value[4].data = waveData.map((item) => {
            // item[1]
            if (item) {
              return item[1];
            } else {
              return 0;
            }
          });
          rows.value[3].data.forEach((item, index) => {
            for (let i = 0; i < wave.length; i++) {
              if (item.toFixed(1) < wave[i].value) {
                rows.value[3].background[index] = wave[i].color;
                break;
              }
            }
          });
        }

        if (res[1].data.code == 200) {
          let windData = res[1].data.data.windDatas;
          rows.value[1].data = windData.map((item) => {
            // item[0]
            if (item) {
              return item[0];
            } else {
              return 0;
            }
          });
          rows.value[2].data = windData.map((item) => {
            // item[1]
            if (item) {
              // return 360 - (item[1] + 90);
              return item[1] + 180;
            } else {
              return 0;
            }
          });
          // rows.value[2].data = windData.map((item) => 360-(item[1]+90));
          rows.value[1].data.forEach((item, index) => {
            for (let i = 0; i < wind_speed.length; i++) {
              if (item?.toFixed(1) < wind_speed[i].value) {
                rows.value[1].background[index] = wind_speed[i].color;
                break;
              }
              rows.value[1].background[index] =
                wind_speed[wind_speed.length - 1].color;
            }
          });
        }

        if (res[2].data.code == 200) {
          let currentData = res[2].data.data.currentDatas;
          rows.value[5].data = currentData.map((item) => {
            // item[0]
            if (item) {
              return item[0];
            } else {
              return 0;
            }
          });
          rows.value[6].data = currentData.map((item) => {
            // item[1]
            if (item) {
              return item[1] + 180;
            } else {
              return 0;
            }
          });

          rows.value[5].data.forEach((item, index) => {
            for (let i = 0; i < current_speed.length; i++) {
              if (item.toFixed(1) < current_speed[i].value) {
                rows.value[5].background[index] = current_speed[i].color;
                break;
              }
            }
          });
        }

        // 所有isShow=true
        rows.value.forEach((item) => {
          item.isShow = true;
        });

        titles.value.forEach((item) => {
          item.isShow = true;
        });

        num.value = 3;

        if (rows.value[5].data.filter((item) => item > 0).length == 0) {
          rows.value[5].isShow = false;
          rows.value[6].isShow = false;

          titles.value[6].isShow = false;
          titles.value[7].isShow = false;

          num.value--;
        }

        if (rows.value[1].data.filter((item) => item > 0).length == 0) {
          rows.value[1].isShow = false;
          rows.value[2].isShow = false;

          titles.value[2].isShow = false;
          titles.value[3].isShow = false;

          num.value--;
        }

        if (rows.value[3].data.filter((item) => item > 0).length == 0) {
          rows.value[3].isShow = false;
          rows.value[4].isShow = false;

          titles.value[4].isShow = false;
          titles.value[5].isShow = false;

          num.value--;
        }

        // 在所有数据处理完成后初始化echarts
        nextTick(() => {
          const chartDom = document.getElementById('chart1');
          const myChart = echarts.init(chartDom);
          
          const option = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross',
                label: {
                  backgroundColor: '#6a7985'
                }
              },
              formatter: function(params) {
                let result = params[0].axisValue + '<br/>';
                params.forEach(item => {
                  result += `${item.marker} ${item.seriesName}: ${item.value.toFixed(2)}${item.seriesName === '海风' ? 'm/s' : item.seriesName === '海浪' ? 'm' : 'm/s'}<br/>`;
                });
                return result;
              }
            },
            legend: {
              data: ['海风', '海浪', '海流'],
              textStyle: {
                color: '#333'
              },
              top: 10
            },
            grid: {
              left: '2%',
              right: '5%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: rows.value[0].data.map((hour, index) => {
                const currentDate = day3.value[Math.floor(index/24)].date;
                // 从 yyyy-MM-dd 格式中提取月和日
                const [_, month, day] = currentDate.split('-');
                return `${month}月${day}日${hour}时`;
              }),
              axisLabel: {
                interval: 3,
                // rotate: 45
              }
            },
            yAxis: [
              {
                type: 'value',
                name: '海风(m/s)',
                position: 'left',
                splitLine: {
                  lineStyle: {
                    type: 'dashed'
                  }
                }
              },
              {
                type: 'value',
                name: '海浪(m)',
                position: 'right',
                offset: 80,
                splitLine: {
                  show: false
                }
              },
              {
                type: 'value',
                name: '海流(m/s)',
                position: 'right',
                splitLine: {
                  show: false
                }
              }
            ],
            series: [
              {
                name: '海风',
                type: 'line',
                data: rows.value[1].data,
                yAxisIndex: 0,
                smooth: true,
                symbol: 'circle',
                showSymbol: false,
                symbolSize: 6,
                lineStyle: {
                  width: 2,
                  color: '#409EFF'
                },
                itemStyle: {
                  color: '#409EFF'
                },
                areaStyle: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                      offset: 0,
                      color: 'rgba(64,158,255,0.3)'
                    }, {
                      offset: 1,
                      color: 'rgba(64,158,255,0)'
                    }]
                  }
                }
              },
              {
                name: '海浪',
                type: 'line',
                data: rows.value[3].data,
                showSymbol: false,
                yAxisIndex: 1,
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: {
                  width: 2,
                  color: '#67C23A'
                },
                itemStyle: {
                  color: '#67C23A'
                },
                areaStyle: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                      offset: 0,
                      color: 'rgba(103,194,58,0.3)'
                    }, {
                      offset: 1,
                      color: 'rgba(103,194,58,0)'
                    }]
                  }
                }
              },
              {
                name: '海流',
                type: 'line',
                data: rows.value[5].data,
                showSymbol: false,
                yAxisIndex: 2,
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: {
                  width: 2,
                  color: '#E6A23C'
                },
                itemStyle: {
                  color: '#E6A23C'
                },
                areaStyle: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                      offset: 0,
                      color: 'rgba(230,162,60,0.3)'
                    }, {
                      offset: 1,
                      color: 'rgba(230,162,60,0)'
                    }]
                  }
                }
              }
            ]
          };

          myChart.setOption(option);
        });
      });
      
    } else {
      activeHeight.value = 0;
      // 清空数据
      rows.value.forEach((item, idx) => {
        if (idx == 0) {
          return;
        }
        item.data = [];
        item.background = [];
      });
    }
  },
  {
    deep: true,
  }
);

// watch(smInfo,()=>{
// },{
//     deep:true,
//     immediate:true
// })
</script>

<template>
  <div class="chartpop" :style="{ height: activeHeight == 0 ? activeHeight : activeHeight + 250 + 'px' }">
    <div id="main_contain" :style="{ height: activeHeight + 'px' }">
      <div id="chartpop_left">
        <div class="chartpop_h" v-for="item in titles" v-show="item.isShow">
          <template v-if="item.title == 'x'">
            <div id="chartpop_header_close">
              <img :src="iconClose" alt="" @click="chartInfo.isChart = false" />
            </div>
          </template>
          <template v-else>
            <span class="chartpop_h_t">{{ item.title }}</span>
            <span class="chartpop_h_dw">{{ item.dw }}</span>
          </template>
        </div>
      </div>
      <el-scrollbar id="chartpop_right" style="height: 100%">
        <div id="chartpop_right_main">
          <div id="chartpop_header">
            <div id="chartpop_header_date">
              <div v-for="item in day3" :key="item.date" class="chartpop_header_date_item"
                :style="{ flex: item.width }">
                {{ item.date }}
              </div>
            </div>
          </div>
          <div id="chartpop_main">
            <div v-for="item in rows" class="chartpop_item" v-show="item.isShow">
              <div class="chartpop_v" :style="{
                background: item.background
                  ? getLinearGradient(item.background)
                  : '',
              }">
                <div v-for="(data, idx) in item.data" class="chartpop_v_item">
                  <template v-if="item.title.includes('向')">
                    <img :src="iconArrow" alt="" :style="{ transform: `rotate(${data}deg)` }" />
                    <!-- {{ data.toFixed(2) }} -->
                  </template>
                  <template v-else-if="
                    item.title == '海风' ||
                    item.title == '海流' ||
                    item.title == '海浪'
                  ">
                    <span :style="{ color: item.title == '海浪' ? getWaveColor(data) : '' }">{{ data.toFixed(2) }}</span>
                  </template>
                  <template v-else>
                    <span :class="idx == diff ? 'date_active' : ''">{{
                      data
                      }}</span>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>

    </div>
    <div style="height: 250px;" id="chart1">

    </div>
  </div>

</template>

<style lang="less" scoped>
.chartpop {
  // height: 240px;
  height: 400px;
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 1000;
  background-color: var(--el-color-Fill-Base);

  #main_contain {
    box-shadow: 0 -5px 10px rgba(0, 0, 0, 0.1);
    display: flex;
    // flex-direction: column;
    transition: all 0.3s;
    overflow: auto;
  }

  // 定义宽度变量100px
  --chartpop_w: 80px;

  .active_border {
    border-left: 1px solid #f5a623;
    border-right: 1px solid #f5a623;
  }

  .date_active {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 7px;
    // 醒目的背景和边框
    background: #f8e71c;
    // color: #fff;
    // 边框
    // border: 1px solid #7ed321;
    // 阴影
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  }

  #chartpop_left {
    width: var(--chartpop_w);
    display: flex;
    flex-direction: column;

    .chartpop_h {
      flex: 1;
      background: var(--el-color-Fill-Darker);
      display: flex;
      align-items: center;
      justify-content: center;
      border-right: 1px solid var(--el-color-Fill-Lighter);

      #chartpop_header_close {
        width: var(--chartpop_w);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;

        img {
          width: 20px;
          height: 20px;
        }
      }

      // 第一个元素高度height: 35px
      &:first-child {
        height: 35px !important;
        flex: none;
        border-top: none;
      }

      .chartpop_h_t {
        font-size: 12px;
        font-family: "alimama";
        font-weight: normal;
        text-align: left;
        white-space: nowrap;
        line-height: 14px;
        // color: var(--el-color-text-secondary);
      }

      .chartpop_h_dw {
        font-size: 12px;
        font-family: "alimama";
        white-space: nowrap;
        line-height: 14px;
        // margin-left: 5px;
        // width: 22px;
        text-align: center;
        // // 虚线下划线
        // border-bottom: 1px dashed var(--el-color-text-secondary);
        // // 第一个元素无下划线
        // &:first-child {
        //     border-bottom: none !important;
        // }
      }
    }
  }

  :deep(.el-scrollbar__wrap) {
    display: flex;
  }

  #chartpop_right_main {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 2800px;
    height: 100%;
  }

  #chartpop_header {
    height: 35px;
    background: var(--el-color-Fill-Lighter);
    display: flex;
    align-items: center;

    #chartpop_header_date {
      height: 100%;
      flex: 1;
      display: flex;
      align-items: center;
      font-size: 12px;
      // font-family: PangMenZhengDao;
      font-family: "aliph500";
      font-weight: normal;
      text-align: left;
      white-space: nowrap;
      line-height: 14px;
      color: var(--el-color-text-regular);

      .chartpop_header_date_item {
        height: 70%;
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        // 除了最后一个都加右边框
        border-right: 1px solid #3466c5;

        &:last-child {
          border-right: none;
        }
      }
    }
  }

  #chartpop_main {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding-right: 5px;
    height: 100%;

    .chartpop_item {
      display: flex;
      flex: 1;

      .chartpop_h {
        width: var(--chartpop_w);
        background: var(--el-color-Fill-Light);
        display: flex;
        align-items: center;
        justify-content: center;
        border-right: 1px solid var(--el-color-Fill-Lighter);

        .chartpop_h_t {
          font-size: 12px;
          font-family: PangMenZhengDao;
          font-weight: normal;
          text-align: left;
          white-space: nowrap;
          line-height: 14px;
          color: var(--el-color-text-secondary);
        }

        .chartpop_h_dw {
          font-size: 12px;
          font-family: PangMenZhengDao;
          font-weight: normal;
          text-align: left;
          white-space: nowrap;
          line-height: 14px;
          margin-left: 5px;
          // 虚线下划线
          border-bottom: 1px dashed var(--el-color-text-secondary);
        }
      }

      .chartpop_v {
        flex: 1;
        display: flex;
        // border-right: 1px solid var(--el-color-Fill-Lighter);
        align-items: center;

        img {
          width: 17px;
          height: 17px;
          user-select: none;
        }

        .chartpop_v_item {
          flex: 1;
          // border-left: 1px solid #F5A623;
          height: 100%;
          font-size: 13px;
          font-family: "aliph400";
          // color: var(--el-color-text-primary);
          color: #000;
          // 阴影
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }
}
</style>
